package hhm.android.my

import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.LogUtils
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.utils.*
import hhm.android.my.databinding.ActivityBabyProfileBinding
import siau.android.base.*
import siau.android.base.BottomSingleGenderSelectSheet.Companion.SELECT_MAN
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import siau.android.http.model.ChildIdModel
import siau.android.http.model.ChildModel
import siau.android.library.FileUtil
import siau.android.library.KeyString
import java.text.SimpleDateFormat
import java.util.*

@Route(path = BABY_ROUTE)
class BabyProfileActivity : SBBaseActivity() {

    companion object {
        val TYPE_CREATE = 0
        val TYPE_CHANGE = 1
    }

    lateinit var dataBinding: ActivityBabyProfileBinding
    private var pageType = TYPE_CREATE
    private var canClick = false
    private var hasChange = false
    private lateinit var childData: ChildModel
    private var childId = -1
    private var bottomSingleSexSelectSheet: BottomSingleGenderSelectSheet? = null
    var weightCla = ""
    var heightCla = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_baby_profile)
        initTitleWithLine(getString(R.string.baby_profile))
        dataBinding.lifecycleOwner = this

        when (SBApplication.userData.weightUnit) {
            WeightClass.KG.msg -> weightCla = getString(R.string.class_kg)
            WeightClass.JIN.msg -> weightCla = getString(R.string.class_jin)
            WeightClass.LB.msg -> weightCla = getString(R.string.class_bang)
        }
        when (SBApplication.userData.heightUnit) {
            HeightClass.CM.msg -> heightCla = getString(R.string.class_cm)
            HeightClass.FT.msg -> heightCla = getString(R.string.class_ft)
        }

        pageType = intent.getIntExtra(KeyString.type, TYPE_CREATE)
        if (pageType == TYPE_CREATE) {
            dataBinding.activityBabyProfileBtn.visibility = View.VISIBLE
            childData = ChildModel(-1, "", "", false, SBApplication.userData.familyId, 0, 0, -1.0, -1.0)
            bottomSingleSexSelectSheet = BottomSingleGenderSelectSheet(this, SELECT_MAN, object : GetStringListener {
                override fun getString(s: String) {
                    dataBinding.activityBabyProfileSexTv.text = s
                    if (s == getString(R.string.boy)) {
                        childData.sex = 1
                    } else {
                        childData.sex = 2
                    }

                    if (pageType == TYPE_CREATE) {
                        checkCanClick()
                    } else {
                        updateData()
                    }
                }
            })
        } else {
            childId = intent.getIntExtra(KeyString.childId, -1)
            dataBinding.activityBabyProfileBtn.visibility = View.GONE
            initData()
        }

        dataBinding.activityBabyProfileName.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                getStringDialog(this, getString(R.string.input_nike_name), dataBinding.activityBabyProfileNameTv.text.toString(), object : GetStringListener {
                    override fun getString(s: String) {
                        dataBinding.activityBabyProfileNameTv.text = s
                        childData.nickName = s

                        if (pageType == TYPE_CREATE) {
                            checkCanClick()
                        } else {
                            updateData()
                        }
                    }
                })
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }
        dataBinding.activityBabyProfileSex.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                bottomSingleSexSelectSheet?.show()
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }
        dataBinding.activityBabyProfileBirthday.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                DialogUtils.showDatePicBottomView(
                    this,
                    object : GetDateListener {
                        override fun getDate(date: Date, string: String) {
                            dataBinding.activityBabyProfileBirthdayTv.text = string
                            childData.birthday = date.time

                            if (pageType == TYPE_CREATE) {
                                checkCanClick()
                            } else {
                                updateData()
                            }
                        }
                    },
                    "yyyy/MM/dd",
                    DateParams.TYPE_YEAR, DateParams.TYPE_MONTH, DateParams.TYPE_DAY,
                )
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }
        dataBinding.activityBabyProfileBirthdayHeight.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                DialogUtils.showHeightPicBottomView(this, SBApplication.userData.heightUnit, childData.height, object : GetStringListener {
                    override fun getString(s: String) {
                        dataBinding.activityBabyProfileBirthdayHeightTv.text = analyseDataBeforeSet(s, 2, heightCla)
                        childData.height = s.replace("cm", "").toDouble()
                        if (pageType == TYPE_CREATE) {
                            checkCanClick()
                        } else {
                            updateData()
                        }
                    }
                })
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }
        dataBinding.activityBabyProfileBirthdayWeight.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                DialogUtils.showWeightPicBottomView(this, SBApplication.userData.weightUnit, childData.weight, object : GetStringListener {
                    override fun getString(s: String) {
                        dataBinding.activityBabyProfileBirthdayWeightTv.text = analyseDataBeforeSet(s, 1, weightCla)
                        childData.weight = s.replace("kg", "").toDouble()
                        if (pageType == TYPE_CREATE) {
                            checkCanClick()
                        } else {
                            updateData()
                        }
                    }
                })
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }

        val takePhotoResult = registerForActivityResult(TakePhotoActivityResultContact()) {
            if (it.resultCode != RESULT_OK) {
                return@registerForActivityResult
            }
            if (!TextUtils.isEmpty(TakePhotoPopWindowUtils.mTempPhotoPath)) {
                showLoadingFragment(R.id.activity_baby_profile_fl)

                //将图片显示在ivImage上
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(TakePhotoPopWindowUtils.mTempPhotoPath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        TakePhotoPopWindowUtils.mTempPhotoPath = ""
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if (info.isOK) {

                            removeLoadingFragment()
                            childData.avatar = authTokenResponse.domain + key
                            GlideUtils.loadCircleImageNoCache(this, childData.avatar, dataBinding.activityBabyProfileIv, R.mipmap.take_picture, R.mipmap.take_picture)
                            if (pageType == TYPE_CREATE) {
                                checkCanClick()
                            } else {
                                updateData()
                            }

                        } else {
                            LogUtils.Companion.i("qiniu", "Upload Fail")
                            removeLoadingFragment()
                        }
                    }, null)

                }, { throwable ->
                    removeLoadingFragment()
                    showToast(throwable.message)
                })
            }
        }
        val selectPicResult = registerForActivityResult(TakePhotoActivityResultContact()) {

            if (it.intent == null || it.intent!!.data == null) {
                return@registerForActivityResult
            }
            showLoadingFragment(R.id.activity_baby_profile_fl)
            val uri: Uri = it.intent?.data!!
            val filePath: String = FileUtil.getFilePathByUri(this, uri)

            if (!TextUtils.isEmpty(filePath)) {
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(filePath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if (info.isOK) {

                            removeLoadingFragment()
                            childData.avatar = authTokenResponse.domain + key
                            GlideUtils.loadCircleImageNoCache(this, childData.avatar, dataBinding.activityBabyProfileIv, R.mipmap.take_picture, R.mipmap.take_picture)
                            if (pageType == TYPE_CREATE) {
                                checkCanClick()
                            } else {
                                updateData()
                            }

                        } else {
                            LogUtils.Companion.i("qiniu", "Upload Fail")
                            removeLoadingFragment()
                        }
                    }, null)

                }, { throwable ->
                    removeLoadingFragment()
                    showToast(throwable.message)
                })
            } else {
                removeLoadingFragment()
            }
        }

        dataBinding.activityBabyProfileIv.setOnClickListener {
            if (SBApplication.userData.isCreator == 1) {
                TakePhotoPopWindowUtils.takePhoto(this, dataBinding.activityBabyProfileBody, takePhotoResult, selectPicResult)
            } else {
                showToast(getString(R.string.u_can_not_change_baby_info))
            }
        }

        dataBinding.activityBabyProfileBtn.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (canClick) {
                    showLoadingDialog()
                    HttpHelper().addChild(childData)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                        hideLoadingDialog()
                        childData.childId = it.childId
                        SBApplication.userData.children?.add(childData)
                        SBApplication.userData.children?.forEach { i ->
                            i.select = false
                        }
                        SBApplication.userData.children!![0].select = true
                        setResult(1001)
                        finish()
                    }, {
                        hideLoadingDialog()
                        showToast(it.message)
                    })
                }
            }
        })
    }

    private fun updateData() {
        showLoadingFragment(R.id.activity_baby_profile_fl)
        HttpHelper().editChild(childData)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            hasChange = true
            initData()
            removeLoadingFragment()
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    override fun finish() {
        if (hasChange) {
            setResult(1001)
        }
        super.finish()
    }

    private fun initData() {
        showLoadingFragment(R.id.activity_baby_profile_fl)
        val r = ChildIdModel(childId)
        HttpHelper().getChildInfo(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            childData = it
            dataBinding.activityBabyProfileNameTv.text = childData.nickName
            dataBinding.activityBabyProfileSexTv.text = if (childData.sex == 2) {
                getString(R.string.girl)
            } else {
                getString(R.string.boy)
            }
            val sdf = SimpleDateFormat("yyyy/MM/dd")
            dataBinding.activityBabyProfileBirthdayTv.text = sdf.format(childData.birthday)
            dataBinding.activityBabyProfileBirthdayHeightTv.text = if (childData.height == null) {
                getString(R.string.please_select)
            } else {
                analyseDataBeforeSet(childData.height.toString(), 2, heightCla)
            }
            dataBinding.activityBabyProfileBirthdayWeightTv.text = if (childData.weight == null) {
                getString(R.string.please_select)
            } else {
                analyseDataBeforeSet(childData.weight.toString(), 1, weightCla)
            }
            if (!TextUtils.isEmpty(childData.avatar)) {
                GlideUtils.loadCircleImageNoCache(this, childData.avatar, dataBinding.activityBabyProfileIv, R.mipmap.take_picture, R.mipmap.take_picture)
            }

            bottomSingleSexSelectSheet = BottomSingleGenderSelectSheet(this, childData.sex, object : GetStringListener {
                override fun getString(s: String) {
                    dataBinding.activityBabyProfileSexTv.text = s
                    if (s == getString(R.string.boy)) {
                        childData.sex = 1
                    } else {
                        childData.sex = 2
                    }

                    if (pageType == TYPE_CREATE) {
                        checkCanClick()
                    } else {
                        updateData()
                    }
                }
            })

            removeLoadingFragment()
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun checkCanClick() {
        if (childData.nickName.isNotEmpty() && (childData.sex == 1 || childData.sex == 2) && childData.birthday !== 0L) {
            canClick = true
            dataBinding.activityBabyProfileBtn.setBackgroundResource(R.drawable.rectangle_circle_maincolor)
        } else {
            canClick = false
            dataBinding.activityBabyProfileBtn.setBackgroundResource(R.drawable.rectangle_circle_grey)
        }
    }

}